/**
 *
 */
package cn.hg.jfsa.manage.controller.system;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.SessionThreadLocal;
import cn.hg.jfsa.manage.controller.system.validator.RoleValidator;
import cn.hg.jfsa.manage.service.JfsaResourceService;
import cn.hg.jfsa.manage.service.JfsaRoleService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.model.JfsaRole;
import cn.hg.jfsa.model.JfsaRoleResource;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.*;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author Golly
 *
 */
public class JfsaRoleController extends BaseController {

	/**
	 * 角色服务
	 */
	@Inject
	private JfsaRoleService roleService;

	/**
	 * 资源服务
	 */
	@Inject
	private JfsaResourceService resourceService;

	/**
	 * 跳转到新增页面
	 */
	public void add() {
		// 创建新记录
		this.setAttr("role", new JfsaRole().setSortNum(0).setStatus("on"));
	}

	/**
	 * 执行分派权限操作
	 */
	@Before(POST.class)
	public void ajaxAssignResource() {
		JfsaRoleResource bean = this.getBean(JfsaRoleResource.class, "roleResource");

		if (null == bean.getId()) {
			bean.save();
		} else {
			if (StrKit.isBlank(bean.getResourceIds())) {
				bean.delete();
			} else {
				bean.update();
			}
		}
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax删除功能
	 */
	@Before(EvictInterceptor.class)
	@CacheName("jfsaRole")
	public void ajaxDel() {
		// 通过页面传入的ID查找到记录
		JfsaRole bean = JfsaRole.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// ID为1的管理员非常特殊，不允许删除
		if (1 == bean.getId()) {
			this.renderAjaxFailed("1", "ID为1的角色不允许删除！");
			return;
		}

		// 更新记录的状态为删除
		bean.setStatus("del").update();

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax方式取得管理员角色
	 */
	public void ajaxGetRoleResource() {
		JfsaRole bean = JfsaRole.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		List<Record> recordList = Db.find(
				"SELECT r.id, r.parent_id AS parentId, r.`value`, r.`name`, r.type, r.icon, r.remark, r.param, FIND_IN_SET(r.id, rr.resource_ids)>0 AS lay_is_checked, d.`name` AS typeName FROM jfsa_resource AS r LEFT JOIN jfsa_role_resource AS rr ON r.status='on' AND rr.role_id=? LEFT JOIN jfsa_dict AS d ON r.type = d.`value` AND d.parent_id=(SELECT d2.id FROM jfsa_dict AS d2 WHERE d2.key = 'resource_type' ) WHERE r.`status` = 'on' ORDER BY r.parent_id, r.sort_num",
				bean.getId());

		this.renderJson(new LayuiPage(recordList));
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before({RoleValidator.class, EvictInterceptor.class})
	@CacheName("jfsaRole")
	public void ajaxSaveOrUpdate() {
		// 获取页面传入的Bean
		JfsaRole bean = this.getBean(JfsaRole.class, "role");

		JfsaRole exist = JfsaRole.DAO.findFirst("select * from jfsa_role where name = ? and id <> ?", bean.getName(),
				bean.getId());

		if (exist != null) {
			this.renderAjaxFailed("1", "角色名已经存在!请更换其它名称。");
			return;
		}

		JfsaAdmin currAdmin = SessionThreadLocal.getAdmin();

		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if (null == bean.getId()) {
					// 初始化数据
					bean.setCreatedTime(new Date()).setCreatorId(currAdmin.getId());

					// 新建记录
					bean.save();
				} else {
					if (1 == bean.getId()) { // ID为1的管理员状态必须为on
						bean.setStatus("on");
					}

					// 更新记录
					bean.setEditorId(currAdmin.getId()).setEditedTime(new Date()).update();
				}
				return true;
			}
		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}
	}

	/**
	 * Ajax方式查询
	 */
	@Before(CacheInterceptor.class)
	@CacheName("jfsaRole")
	public void ajaxSearch() {
		// 建立查询键值对
		Kv para = Kv.by("key", this.getPara("key")).set("name", this.getPara("name"))
				.set("status", this.getPara("status"))
				.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
				.set("sortType", this.getPara("sortType"));

		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("system.findRole", para);

		// 执行查询
		Page<JfsaRole> page = JfsaRole.DAO.paginate(getParaToInt("page", 1), getParaToInt("limit", 10), sqlPara);

		this.setAttr("sortField", this.getPara("sortField"));
		this.setAttr("sortType", this.getPara("sortType"));

		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到分派权限页面
	 */
	@Before(GET.class)
	public void assignResource() {
		JfsaRole bean = JfsaRole.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		JfsaRoleResource roleResource = JfsaRoleResource.DAO
				.findFirst("SELECT * FROM jfsa_role_resource WHERE role_id=?", this.getParaToInt("id"));

		if (roleResource == null) {
			roleResource = new JfsaRoleResource().setRoleId(bean.getId());
		}

		this.setAttr("role", bean);

		this.setAttr("roleResource", roleResource);
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit() {
		// 查询目标记录
		this.setAttr("role", JfsaRole.DAO.findById(this.getParaToInt("id")));
	}

	/**
	 * 跳转到列表页面
	 */
	@Override
	@Before(CacheInterceptor.class)
	@CacheName("jfsaRole")
	public void index() {
	}

	/**
	 * 跳转到查看页面
	 */
	@Before(CacheInterceptor.class)
	@CacheName("jfsaRole")
	public void view() {
		JfsaRole bean = JfsaRole.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		this.setAttr("role", bean);
	}
}
